package io.renren.modules.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.R;
import io.renren.modules.sys.entity.QianduanYonghu;
import io.renren.modules.sys.entity.dto.UserLoginDto;
import io.renren.modules.sys.service.QianduanYonghuService;
import io.renren.modules.util.Re;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author beisheng
 * @since 2022-09-06
 */
@RestController
@CrossOrigin
@RequestMapping("/yonghu")
public class QianduanYonghuController {

    @Autowired
    private QianduanYonghuService qianduanYonghuService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    JavaMailSenderImpl mailSender;

    @RequestMapping("/getUserByEmail/{email}")
    public R getUserByEmail(@PathVariable("email") String email){

        QianduanYonghu qianduanYonghu = qianduanYonghuService.getOne(new QueryWrapper<QianduanYonghu>().eq("email",email));
        return R.ok().put("user",qianduanYonghu);
    }

    @RequestMapping("/getEmailCode/{email}")
    public R getEmailCode(@PathVariable("email") String email) throws MessagingException {
        int count=1;//默认发送一次
        String codeNum = "";
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        while(count--!=0){
            int [] code = new int[3];
            Random random = new Random();
            //自动生成验证码
            for (int i = 0; i < 6; i++) {
                int num = random.nextInt(10) + 48;
                int uppercase = random.nextInt(26) + 65;
                int lowercase = random.nextInt(26) + 97;
                code[0] = num;
                code[1] = uppercase;
                code[2] = lowercase;
                codeNum+=(char)code[random.nextInt(3)];
            }
            System.out.println(codeNum);
            //标题
            helper.setSubject("您的验证码为："+codeNum);
            //内容
            helper.setText("您好！神州租车提示您。您的验证码为："+"<h2>"+codeNum+"</h2>"+"千万不能告诉别人哦！",true);
            //邮件接收者
            helper.setTo(email);
            //邮件发送者，必须和配置文件里的一样，不然授权码匹配不上
            helper.setFrom("1791201652@qq.com");
            mailSender.send(mimeMessage);
            System.out.println("邮件发送成功！"+(count+1));
            redisTemplate.opsForValue().set("codeNum",codeNum,60, TimeUnit.SECONDS);
        }
        return R.ok().put("codeNum",codeNum);
    }

    @RequestMapping("/Login")
    public Re Login(@RequestBody UserLoginDto userLoginDto){
        String codeNum = (String) redisTemplate.opsForValue().get("codeNum");
        if(codeNum != null && codeNum.equals(userLoginDto.getEmailCode())){
            QianduanYonghu user = qianduanYonghuService.getOne(new QueryWrapper<QianduanYonghu>().eq("email",userLoginDto.getEmail()));
            return Re.ok().data("user",user).code(0).message("登陆成功");
        }else if(codeNum == null) {
            return Re.error().message("邮箱验证码已过期").code(2);
        }else if (!codeNum.equals(userLoginDto.getEmailCode())){
            return Re.error().message("邮箱验证码输入错误").code(1);
        }
        return Re.ok();
    }
    @RequestMapping("/insert")
    public Re insert(@RequestBody UserLoginDto userLoginDto){
        String codeNum = (String) redisTemplate.opsForValue().get("codeNum");
        if(codeNum != null && codeNum.equals(userLoginDto.getEmailCode())){
            QianduanYonghu qianduanYonghu = new QianduanYonghu();
            BeanUtils.copyProperties(userLoginDto,qianduanYonghu);
            qianduanYonghu.setUserName("北笙");
            qianduanYonghu.setAge(18);
            qianduanYonghu.setDelFlag(0);
            qianduanYonghu.setCreateTime(new Date());
            qianduanYonghu.setSex(1);
            qianduanYonghu.setUpdateTime(new Date());
            qianduanYonghu.setImgId(2);
            qianduanYonghuService.save(qianduanYonghu);
            return Re.ok().code(0).message("注册成功");
        }else if (!codeNum.equals(userLoginDto.getEmailCode())){
            return Re.error().message("邮箱验证码输入错误").code(1);
        }else {
            return Re.error().message("邮箱验证已过期").code(2);
        }
    }
}

